package com.xgpro.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author tx
 * @version 1.0
 * @date 2019/11/13 20:55
 */
public class ZipFileTool {

	/**
	 * 将目标文件打包成zip
	 * @param filePaths
	 * @param zipFilePath
	 * @param fileName
	 * @return
	 */
	public static String fileToZip(List<String> filePaths, String zipFilePath, String fileName) {
		String nginxUrl="";
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		File file = null;
		List<File> fileList = new ArrayList<File>();
		for (String filePath : filePaths) {
			file = new File(filePath);
			fileList.add(file);
		}
		try {
			if (!new File(zipFilePath).exists()) {
				new File(zipFilePath).mkdirs();
			}
			File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
			/*
			 * if (zipFile.exists()) { System.out.println(">>>>>> " + zipFilePath +
			 * " 目录下存在名字为：" + fileName + ".zip" + " 打包文件. <<<<<<"); } else {
			 */
			if (null == fileList || fileList.size() < 1) {
				System.out.println("抛异常");
			} else {
				fos = new FileOutputStream(zipFile);
				zos = new ZipOutputStream(new BufferedOutputStream(fos));
				byte[] bufs = new byte[1024 * 10];
				for (int i = 0; i < fileList.size(); i++) {
					// 创建ZIP实体,并添加进压缩包
					ZipEntry zipEntry = new ZipEntry(fileList.get(i).getName());
					zos.putNextEntry(zipEntry);
					// 读取待压缩的文件并写进压缩包里
					fis = new FileInputStream(fileList.get(i));
					bis = new BufferedInputStream(fis, 1024 * 10);
					int read = 0;
					while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
						zos.write(bufs, 0, read);
					}
				}
				nginxUrl = ReadPropertiesUtil.readUrl("zipURL") + "/" + fileName + ".zip";
				/* } */
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			// 关闭流
			try {
				if (null != bis)
					bis.close();
				if (null != zos)
					zos.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}

		return nginxUrl;
	}


	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("C:\\1.txt");
		list.add("C:\\2.txt");
		String zipFilePath = "C:\\home";
		String fileName = "测试";
		String s = ZipFileTool.fileToZip(list, zipFilePath, fileName);
		System.out.println(s);
	}

}
